//
//  main.cpp
//  541.反转字符串II
//
//  Created by Yan Zihao on 2024/9/28.
//

#include <iostream>
#include<string>
#include<algorithm>
using namespace std;

/*class Solution
{
public:
    string reverseStr(string s, int k)
    {
        string s1;
        string s2;
        if(s.size() - k < k)
        {
            for (int i = 0; i < k; i++)
            {
                s1.push_back(s[i]);
            }
            reverse(s1.begin(),s1.end());
            
            for (int j = 0; j < s1.size(); j++)
            {
                s2.push_back(s1[j]);
            }
            
            for (int m = k; m < s.size(); m++)
            {
                s2.push_back(s[m]);
            }
        }
        if(k <= s.size() - k <= 2*k)
        {
            for (int i = 0; i < k; i++)
            {
                s1.push_back(s[i]);
            }
            reverse(s1.begin(),s1.end());
            
            for (int j = 0; j < s1.size(); j++)
            {
                s2.push_back(s1[j]);
            }
            
            for (int m = k; m < s.size(); m++)
            {
                s2.push_back(s[m]);
            }
        }
        
        return s2;
    }
};*/

/*class Solution
{
public:
    string reverseStr(string s, int k)
    {
        int num = s.size() / k;
        if(0 <= num && num <= 1)
        {
            reverse(s.begin(),s.end());
        }
        
        if(1 < num && num < 2)
        {
            reverse(s.begin(),s.begin()+k);
        }
        
        if(num > 2)
        {
            int count = 0;
            for(int i = 0;s.size()-2*k*count < 2*k;i += 2*k)
            {
                reverse(s.begin()+i,s.begin()+i+k);
                count++;
            }
            if(0 <= s.size()-2*k*count && s.size()-2*k*count <= 1)
            {
                reverse(s.begin()+s.size()-2*k*count,s.end());
            }
            
            if(1 < s.size()-2*k*count && s.size()-2*k*count < 2)
            {
                reverse(s.begin()+s.size()-2*k*count,s.begin()+k+s.size()-2*k*count);
            }
        }
        return s;
    }
};*/

class Solution
{
public:
    string reverseStr(string s, int k)
    {
        int n = s.size();
        
        // 每次跳跃 2k 步长
        for (int i = 0; i < n; i += 2 * k)
        {
            // 反转从 i 开始到 i + k 的字符
            // 注意不能超过字符串长度
            if (i + k <= n)
            {
                reverse(s.begin() + i, s.begin() + i + k);
            } else
            {
                // 如果剩余字符少于 k 个，则反转剩余的所有字符
                reverse(s.begin() + i, s.end());
            }
        }
        
        return s;
    }
};
